package com.example.smartcitydemo

import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.commitNow
import java.util.*

/**
 * @PACKAGE_NAME: com.example.smartcitydemo
 * @NAME: Caleb.F
 * @DATE: 2021/11/9 11:12
 * @Email: 1919796283@qq.com
 */
object ActivityManager {

    private val activityList: LinkedList<AppCompatActivity> by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
        LinkedList<AppCompatActivity>()
    }

    fun add(activity: AppCompatActivity) {
        activityList.addFirst(activity)
    }

    fun remove(activity: AppCompatActivity): Boolean {
        if (activity.isFinishing) {
            activity.finish()
        }
        return activityList.remove(activity)
    }

    fun finishAll() {
        activityList.onEach {
            if (!it.isFinishing) {
                val fragmentManager = it.supportFragmentManager
                val myFragments = fragmentManager.fragments
                myFragments.onEach {
                    if (!it.isDetached) {
                        //将其中的fragment立即移除
                        fragmentManager.commitNow(true) {
                            remove(it)
                        }
                    }
                }
                it.finish()
            }
        }
        activityList.clear()
    }
}
